from django.contrib.auth.models import AbstractUser
from django.db import models
from django.urls import reverse
from ctbloge.apps.blog.models import BaseModel
from django.utils import timezone
import requests
from django.conf import settings
from django.http import JsonResponse

class UserProfile(AbstractUser, BaseModel):
    SOURCE_CHOICES = [('web', '网站'), ('qq', 'QQ'),('weixin', '微信'),( 'weibo', '微博'),('github', 'GitHub'),('gitee', 'Gitee')]
    avatar_default = 'default/avatar/avatar.png'
    #身份
    IDENTITY_CHOICES = [ ('admin', '博主/管理员'), ('vip', '会员'),('visitor','游客') ]
    identity = models.CharField('身份', max_length=10, choices=IDENTITY_CHOICES, default='visitor')
    nickname = models.CharField('昵称',max_length=100, blank=True)
    avatar = models.ImageField('头像', upload_to='auth/avatar/%Y-%m-%d/',default=avatar_default, blank=True)
    bio = models.TextField('个人简介', max_length=500, blank=True)
    source = models.CharField('注册来源', max_length=100, choices=SOURCE_CHOICES, blank=True,default='web')
    website = models.URLField('个人网站', max_length=200, blank=True)
    address = models.CharField('地址', max_length=100, blank=True)
    phone = models.CharField('手机号', max_length=11, blank=True)
    weibo = models.CharField('微博', max_length=100, blank=True)
    weibo_id = models.CharField('微博ID', max_length=100, blank=True, null=True)
    qq = models.CharField('QQ', max_length=100, blank=True)
    qq_id = models.CharField('QQ OpenID', max_length=100, blank=True)
    #qq二维码
    qq_qrcode = models.ImageField('QQ二维码', upload_to='auth/qq_qrcode/%Y-%m-%d', blank=True)
    wechat = models.CharField('微信', max_length=100, blank=True)
    wechat_qrcode = models.ImageField('微信二维码', upload_to='auth/wechat_qrcode/%Y-%m-%d', blank=True)
    #微信公众号二维码
    wechat_gzh_qrcode = models.ImageField('微信公众号二维码', upload_to='auth/wechat_gzh_qrcode/%Y-%m-%d', blank=True)
    github = models.CharField('GitHub', max_length=100, blank=True)
    github_id = models.CharField('GitHub ID', max_length=100, blank=True, null=True)
    gitee = models.CharField('Gitee', max_length=100, blank=True)
    gitee_id = models.CharField('Gitee ID', max_length=100, blank=True, null=True)

    def get_absolute_url(self):
        return reverse('user_detail', args=[self.username])
    def __str__(self):
        return self.username
    def save(self, *args, **kwargs):
        if self.github:
            self.github_id = self.get_github_user_id(self.github)
            super(UserProfile, self).save(*args, **kwargs)
        if self.gitee:
            self.gitee_id = self.get_gitee_user_id(self.gitee)
            super(UserProfile, self).save(*args, **kwargs)

        super(UserProfile, self).save(*args, **kwargs)

    def get_unread_notifications(self):
        """获取用户未读通知"""
        return self.notifications.filter(unread=True)

    def get_unread_count(self):
        """获取未读通知数量"""
        return self.get_unread_notifications().count()
    def get_github_user_id(self, github_url):
        # 提取用户名
        username = github_url.split('/')[-1].strip()
        if not username:
            return None

        # 访问GitHub用户信息API
        user_info_url = f"https://api.github.com/users/{username}"
        response = requests.get(user_info_url)

        if response.status_code == 200:
            user_info = response.json()
            return user_info.get('id')
        else:
            return None
    def get_gitee_user_id(self, gitee_url):
        # 提取用户名
        username = gitee_url.split('/')[-1]
        if not username:
            return None
        user_info_url = f"https://gitee.com/api/v5/users/{username}"
        response = requests.get(user_info_url)
        if response.status_code == 200:
            user_info = response.json()
            return user_info.get('id')
        else:
            return None



    class Meta:
        ordering = ['-id']
        verbose_name = '用户列表'
        verbose_name_plural = verbose_name
        get_latest_by = 'id'


class PasswordResetCode(models.Model):
    email = models.EmailField('邮箱')
    code = models.CharField(max_length=6, verbose_name='验证码')
    created_date = models.DateTimeField(default=timezone.now, verbose_name='创建时间')
    is_used = models.BooleanField(default=False, verbose_name='是否已使用')

    def is_expired(self):
        return (timezone.now() - self.created_date).seconds > 600  # 10分钟有效期
